import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/services/screenAdapter.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/index.dart';

class ShopDetailController extends GetxController {
  var opcity = 0.0.obs;
  ScrollController scrollController = ScrollController();
  GlobalKey globalKey1 = GlobalKey();
  GlobalKey globalKey2 = GlobalKey();
  GlobalKey globalKey3 = GlobalKey();

  final List<String> segments = ["商品", "详情", "推荐"];
  var segmentIndex = 0.obs;

  TextEditingController buyNumController =
      TextEditingController.fromValue(const TextEditingValue(text: "1"));
  var shopModel = ShopModel().obs;
  var attrList = <Map<String, dynamic>>[].obs;

  final List<String> subSegments = ["商品介绍", "规格参数"];
  var subSegmentIndex = 0.obs;

  double gk2Position = 0;
  double gk3Position = 0;
  RxBool showSubSegment = false.obs;

  var bestShopList = <ShopModel>[].obs;

  @override
  void onInit() {
    super.onInit();
    getDetailData();
    getBestShopListData();
    addScrollControllerListener();
  }

  addScrollControllerListener() {
    scrollController.addListener(() {
      // 获取渲染后元素的位置
      getContainerPosition(scrollController.position.pixels);

      // 根据滑动的位置，控制 tab 的 下标
      if (scrollController.position.pixels > gk2Position &&
          scrollController.position.pixels < gk3Position) {
        if (showSubSegment.value == false) {
          showSubSegment.value = true;
          segmentIndex.value = 1;
        }
      } else if (scrollController.position.pixels > 0 &&
          scrollController.position.pixels < gk2Position) {
        if (showSubSegment.value == true) {
          showSubSegment.value = false;
          segmentIndex.value = 0;
        }
      } else if (scrollController.position.pixels > gk3Position) {
        if (showSubSegment.value == true) {
          showSubSegment.value = false;
          segmentIndex.value = 2;
        }
      }

      // 根据滑动的位置，控制是否显示 tab
      if (scrollController.position.pixels <= 100 &&
          scrollController.position.pixels > 0) {
        opcity.value = scrollController.position.pixels / 100;
      } else if (scrollController.position.pixels <= 0) {
        opcity.value = 0;
      } else if (scrollController.position.pixels > 100) {
        opcity.value = 1;
      }
    });
  }

  getContainerPosition(pixels) {
    RenderBox box2 = globalKey2.currentContext!.findRenderObject() as RenderBox;
    // localToGlobal 获取到的是距离手机顶部的距离，如果要从0开始计算就要加上滚动条下啦的高度
    gk2Position = box2.localToGlobal(Offset.zero).dy +
        pixels -
        (ScreenUtil().statusBarHeight + ScreenAdapter.height(120));

    RenderBox box3 = globalKey3.currentContext!.findRenderObject() as RenderBox;
    gk3Position = box3.localToGlobal(Offset.zero).dy +
        pixels -
        (ScreenUtil().statusBarHeight + ScreenAdapter.height(120));
  }

  selectSegmentIndex(int index) {
    segmentIndex.value = index;
    switch (index) {
      case 0:
        Scrollable.ensureVisible(globalKey1.currentContext!,
            duration: const Duration(milliseconds: 250));
        break;
      case 1:
        Scrollable.ensureVisible(globalKey2.currentContext!,
            duration: const Duration(milliseconds: 250), alignment: 0.25);
        break;
      case 2:
        Scrollable.ensureVisible(
          globalKey3.currentContext as BuildContext,
          duration: const Duration(milliseconds: 500),
        );
        break;
      default:
    }
  }

  selectSubSegmentIndex(int index) {
    subSegmentIndex.value = index;
    // 跳转到详情位置
    scrollController.jumpTo(gk2Position);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  getDetailData() {
    XHttp.getInstance()
        .get(Api.pcontent, {"id": Get.arguments["id"]}).then((value) {
      Result result = value;
      Map<String, dynamic> data = result.data["result"] as Map<String, dynamic>;
      shopModel.value = ShopModel.fromJson(data);
      for (ShopAttrModel attrModel in shopModel.value.attr!) {
        List<ShopAttrItemModel> tempList = [];
        for (String title in attrModel.list!) {
          int index = attrModel.list!.indexOf(title);
          ShopAttrItemModel itemModel = ShopAttrItemModel();
          itemModel.title = title;
          itemModel.selected = index == 0 ? true : false;
          tempList.add(itemModel);
        }
        attrList.add({"title": attrModel.cate, "list": tempList});
      }
    });
  }

  // 优惠商品推荐
  void getBestShopListData() {
    XHttp.getInstance().get(Api.shopList, {"is_best": 1}).then((value) {
      Result result = value as Result;
      List list = result.data["result"] as List;
      bestShopList.value = list
          .map((e) => ShopModel.fromJson(e as Map<String, dynamic>))
          .toList();
    });
  }

  selectedAttr(String title, String attr) {
    print(title);
    for (Map map in attrList.value) {
      if (map['title'] == title) {
        for (ShopAttrItemModel model in map['list']) {
          model.selected = model.title == attr;
          print(model.selected);
        }
      }
    }
    update();
  }
}
